package com.android.DroidBookGallery.Utils;

import java.net.URI;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class HTTP {

	private static HTTP instance;

	private HTTP() {

	}

	public static HTTP getInstance() {
		if (instance == null)
			instance = new HTTP();
		return instance;
	}

	// @EstadoDevelop("testado")
	public String GET(String getUrl) {
		String result = "";
		try {
			HttpClient client = new DefaultHttpClient();
			URL url = new URL(getUrl);
			URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(),
					url.getQuery(), null);
			HttpGet get = new HttpGet(uri);
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result;
	}

	// @EstadoDevelop("testado")
	public String POST(String endpoint, List<NameValuePair> parameters) {
		String result = "";
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(endpoint);
			UrlEncodedFormEntity ent = new UrlEncodedFormEntity(parameters,
					org.apache.http.protocol.HTTP.UTF_8);
			post.setEntity(ent);
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return result;
	}

}